﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MultiClassDBA.ChannelBuilder
{

    /* The idea behind this is to provide a quick way to parse SQL scripts. It's not guaranteed to be correct, 
     * especially if parts of the mask are short/common strings. So it might split the string it's parsing in the wrong
     * spot. But most of the time it works just fine.
     * 
     * Anyways, the mask is a list of strings that you know are going to show up
     * in the string you're parsing. The parser returns an array containing the substrings that occurred between the strings 
     * in the mask. Simple as that.
     * 
     * Ex: 
     *     mask: {"FirstName: ","LastName: ","END"}
     *     input string: "FirstName: Gabe LastName: Buckmaster END"
     *     returns: {"Gabe", "Buckmaster"}
     */

    class MaskParser
    {
        public List<String> mask;

        public MaskParser(List<String> mask)
        {
            this.mask = mask;
            for (int i = 0; i < mask.Count; i++)
                mask[i] = mask[i].Replace(" ", "");
        }

        public bool fitsMask(String s)
        {
            int a = 0;
            foreach (String c in mask)
            {
                a = s.IndexOf(c, a);
                if (a == -1)
                    return false;
                a += c.Length;
            }
            return true;
        }

        public List<String> parse(String s)
        {
            //Remove spaces
            s = s.Replace(" ", "");

            List<String> rv = new List<String>();
            int a = 0;
            int b = 0;
            for (int i = 0; i < mask.Count - 1; i++)
            {
                a = s.IndexOf(mask[i], a);
                if (a == -1)
                    throw new Exception("Error: input string does not match mask. Check first using MaskParser.fitsMask()");
                a += mask[i].Length;
                b = s.IndexOf(mask[i + 1], a);
                if (b == -1)
                    throw new Exception("Error parsing input string.");
                rv.Add(s.Substring(a, b - a));
            }
            return rv;
        }
    }
}
